package com.hyt.it.ogt.kq.common.gov.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.core.RedisTemplate;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *
 * </p>
 *
 * @author Chengxh
 * @since 2021-08-14
 */
@EnableCaching
@Configuration
public class RedisCacheConfig {
	
	@Value("${monitor.cacheTtl}")
	private Long monitorCacheTtl;
	
	@SuppressWarnings("rawtypes")
	@Autowired
    private RedisTemplate redisTemplate;

    @Bean
    public RedisCacheWriter writer() {
        return RedisCacheWriter.nonLockingRedisCacheWriter(redisTemplate.getConnectionFactory());
    }

    @Bean
    public CacheManager cacheManager() {
        Map<String, RedisCacheConfiguration> configurationMap = new HashMap<>(2);
        //考试监控分页缓存
        configurationMap.put("monitor_page", RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofSeconds(monitorCacheTtl)));

        return RedisCacheManager.builder(writer())
                .initialCacheNames(configurationMap.keySet())
                .withInitialCacheConfigurations(configurationMap)
                .build();
    }

}
